package Task2;

public class SortedIntList implements SortedIntListInterface {

	private Item head;
	
	public SortedIntList(Item _head){
		head = _head;
		
	}
	
	public SortedIntList(){
		head = null;
	}
	@Override
	public boolean isEmpty() {
		if(head==null)
			return true;
		return false;
	}

	@Override
	public int size() {
		if (this.isEmpty())
			return 0;
		int size = 1;
		Item currentItem = head;
		while (currentItem.hasNext()){
			currentItem = currentItem.next();
			size += 1;
		}
		
		return size;
	}

	@Override
	public void add(int val) {
		if (this.isEmpty()){
			head = new Item(val);
			return;
		}
		else if (head.value() == val){
			return;
		}
		else if (head.value() > val){
			head = new Item(val, head);
			return;
		}
		Item currentItem = head;
		while (currentItem.hasNext()){
			if (currentItem.next().value() == val){
				return;
			}
			if (currentItem.next().value() > val){
				currentItem.setNext(new Item(val, currentItem.next()));
				return;
			}
			currentItem = currentItem.next();
		}
		currentItem.setNext(new Item(val));
		
	}

	@Override
	public void delete(int val) {
		Item currentItem = head;
		if (val == head.value()){
			head = head.next();
			return;
		}
		while (currentItem.hasNext()){
			if (currentItem.next().value() == val){
				currentItem.setNext(currentItem.next().next());
				return;
			}
			currentItem = currentItem.next();
		}
		//item does not exist!
		
	}

	@Override
	public void clear() {
		head = null;
		
	}

	@Override
	public int getPosition(int x) {
		Item currentItem = head;
		int position = 0;
		while (currentItem.hasNext()){
			if (currentItem.value() == x){
				break;
			}
			currentItem = currentItem.next();
			position++;
		}
		return position;
	}

	@Override
	public int get(int i) {
		if (this.isEmpty()){
			return -1;
		}
		Item currentItem = head;
		int counter = 0;
		while (counter != i){
			currentItem = currentItem.next();
			counter++;
		}

		return currentItem.value();
	}

	@Override
	public int[] toArray() {
		int[] array = new int[this.size()];
		if (this.isEmpty()){
			return array;
		}

		Item currentItem = head;
		int index = 0;
		//used dowhile to confuse self and markers
		do{
			array[index] = currentItem.value();
			if(!currentItem.hasNext()){
				break;
			}
			currentItem = currentItem.next();
			index++;
		}
		while (currentItem.hasNext());
		
		array[index] = currentItem.value();
		return array;
	}
   // for even more debugging statements!
	public String toString() {
		String retString = "";
		int[] arr = this.toArray();
		for (int i : arr){
			retString += i + " ";
		}
		return retString;
	}
}